package com.kexinde.wjifen.util;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;

import org.apache.commons.io.FileUtils;

public class CreateUploadPath {
	private File upload;// 实际上传文件

	private String uploadContentType; // 文件的内容类型

	private String uploadFileName; // 上传文件名

	private ServletContext context;

	private ServletRequest request;

	private String path = "upload/default.jpeg";

	private int flag;

	public CreateUploadPath(File upload, String uploadContentType,
			ServletContext context, ServletRequest request, int flag) {
		this.upload = upload;
		this.uploadContentType = uploadContentType;
		this.context = context;
		this.request = request;
		this.flag = flag;
	}

	public String execute() throws Exception {
		if (upload != null) { // 判断是否有上传图片
			if ("image".equals(uploadContentType.substring(0, 5))) { // 判断是否为图片格式
				try {
					String targetDirectory;
					if (flag == 0)
						targetDirectory = context.getRealPath("/upload");
					else
						targetDirectory = context
								.getRealPath("/shopadmin/upload");
					String[] ip = request.getRemoteAddr().split("\\.|:");
					StringBuilder sb = new StringBuilder();
					for (int i = 0; i < ip.length; i++) {
						sb.append(ip[i]);
					}
					SimpleDateFormat sdf = new SimpleDateFormat(
							"yyyyMMddHHmmss");
					sb.append(sdf.format(new Date()));
					sb.append('.' + uploadContentType.substring(6));
					String targetFileName = sb.toString(); // 按ip+日期时间命名上传图片
					File target = new File(targetDirectory, targetFileName);
					FileUtils.copyFile(upload, target);
					this.setUploadFileName(target.getPath()); // 保存文件的存放路径
						this.path = "upload/" + targetFileName;
				} catch (Exception e) {
					e.printStackTrace();
				}
				return this.path;
			}
		} else { // 没上传图片则使用默认图
			return this.path;
		}
		return this.path;

	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public void setServletContext(ServletContext context) {
		this.context = context;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

}